package com.woniuxy.shop.servelet.front;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniuxy.shop.entity.DetailOrder;
import com.woniuxy.shop.entity.Order;
import com.woniuxy.shop.exception.ServiceException;
import com.woniuxy.shop.service.DetailOrderService;
import com.woniuxy.shop.service.OrderService;

@WebServlet("/alipay")
public class AlipayServlet extends HttpServlet {
	private Properties prop = new Properties();
	static int orderid;
	OrderService os = new OrderService();
	DetailOrderService dos = new DetailOrderService();
	@Override
	public void init() throws ServletException {
		try {
			prop.load(AlipayServlet.class.getResourceAsStream("/alipay.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String opr = request.getParameter("opr");
		if ("pay".equals(opr)) {
			doPay(request, response);
		} else if ("notify".equals(opr)) {
			doNotify(request, response);
		} else if ("return".equals(opr)) {
			doReturn(request, response);
		}
	}

	// 往支付宝的网关方式请求，获取支付我二维码
	private void doPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=" + prop.getProperty("charset"));
		AlipayClient alipayClient = new DefaultAlipayClient(prop.getProperty("gatewayUrl"), prop.getProperty("app_id"),
				prop.getProperty("merchant_private_key"), "json", prop.getProperty("charset"),
				prop.getProperty("alipay_public_key"), prop.getProperty("sign_type"));

		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(prop.getProperty("return_url"));
		alipayRequest.setNotifyUrl(prop.getProperty("notify_url"));
		orderid = Integer.parseInt(request.getParameter("orderid"));
		//获取订单
		Order o = os.getOrder(orderid);
		//获取详细订单
		List<DetailOrder> dors = dos.getDetailOrder(orderid);
		String details = "";
		if(dors!=null) {
			for (DetailOrder dor : dors) {
				details += "商品名："+dor.getGname()+",数量:"+dor.getNums();
			}
		}
		String out_trade_no = o.getOrderno();//request.getParameter("orderNo");
//		String temp  ="￥"+o.getMoney();
		String total_amount = String.valueOf(o.getMoney());
		String subject = "向商家付款";
		String body = details;

		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
				+ "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

		String result = "";
		try {
			//使用java方式HTTP请求，获得响应
			result = alipayClient.pageExecute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			throw new ServiceException("支付失败", e);
		}
		System.out.println(result);
		PrintWriter writer = response.getWriter();
		writer.write(result);
		writer.close();

	}

	private void doReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 到支付提示页面
		response.sendRedirect("pay_suc.jsp");
	}

	private void doNotify(HttpServletRequest request, HttpServletResponse response) {
		os.updataStatus(orderid);
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}
}
